package com.cyou.qb.face.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.cyou.nad.utils.MD5;
import com.cyou.qb.face.entity.ActivityInfo;
import com.cyou.qb.face.entity.Face173AccessLog;
import com.cyou.qb.face.entity.OutService;
import com.cyou.qb.face.entity.trans.ActReturn;
import com.cyou.qb.face.exception.QbGetDataException;
import com.cyou.qb.face.log.IOutServiceLog;
import com.cyou.qb.face.service.QbOperateService;
import com.cyou.qb.face.util.contants.FaceContants;
import com.cyou.qb.face.util.converter.FaceHttpUtil;
import com.cyou.qb.face.util.converter.FaceStringUtil;

@Component("QbOperateImpl")
/**
 * 对QBoperater
 * @author wangwenlong
 *
 */
public class QbOperateServiceImpl extends BaseFaceServiceimpl implements
		QbOperateService {

	@Value("${face.SHOPURL}")
	private String shopURL;
	@Value("${face.getGold}")
	private String getGold;
	@Value("${face.addAct}")
	private String addAct;
	@Value("${face.addActGold}")
	private String addActGold;
	@Value("${face.userReCharge}")
	private String userReCharge;
	@Value("${face.userChargeBack}")
	private String userChargeBack;
	
	Logger logger = Logger.getLogger(QbOperateServiceImpl.class);

	@Autowired
	private IOutServiceLog outServiceLog;
	enum AccountKind {

		/** 消费账户余额 **/
		CONSUME("1", "消费账户余额"),

		/** 分配账户余额 **/
		ALLOT("2", "分配账户余额");

		private String value;

		private String name;

		private AccountKind(String value, String name) {
			this.value = value;
			this.name = name;
		}

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}

	

	/**
	 * <p>
	 * 创建活动并为活动充值
	 * </p>
	 * 
	 * @author wangwenlong
	 * @param passport
	 * @param password
	 * @param gbvalue
	 * @param info
	 * @return ActReturn
	 * @throws QbGetDataException
	 * @throws DocumentException
	 */
	@Override
	public ActReturn applyGb(String passport, String password, int gbvalue,
			ActivityInfo info) throws QbGetDataException, DocumentException {

		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());

		String xmlString = this.addActivitys(info);
		Document doc = null;
		Document doc1 = null;
		Element actIdEle = null;
		Element flagEle = null;
		ActReturn acr = new ActReturn();
		String url="";
		String resultXML = null;
		try {
			// 解析返回的XML
			doc = DocumentHelper.parseText(xmlString);
			Element root = doc.getRootElement();
			flagEle = root.element("flag");
			actIdEle = root.element("act_id");
			acr.setFlag(flagEle.getText());
			acr.setAccId(actIdEle.getText());
			if (acr.getFlag().equals("1")) {
				String message = passport + "#" + password + "#"
						+ actIdEle.getData() + "#" + gbvalue;
				/**
				 * 将信息进行3des加密
				 */
				String message1 = null;
				message1 = DESCoder.desEncrypt(message);

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("message", message1);

				url = FaceStringUtil.createURLString(shopURL + addActGold, map,
						"GBK");
				accessLog.setCallServiceParam(url);
				resultXML = FaceHttpUtil.doRequest(url, null, null,
						FaceContants.GBKENCODE);
				/**
				 * 将返回结果打印日志
				 */
				outServiceLog.getReturnLog(resultXML);
				doc1 = DocumentHelper.parseText(resultXML);
				Element root1 = doc1.getRootElement();
				flagEle = root1.element("flag");
				acr.setFlag(flagEle.getData().toString());
				return acr;
			} else {
				logger.error("create activity false");
				throw new QbGetDataException("create activity false");
			}
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GB);
			outService.setObject("passport:" + passport);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultXML);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("addActivitys throw QbGetDataException" + e.getMessage(), e);
			throw new QbGetDataException("addActivitys throw Exception"+ e.getMessage(), e);
		}
	}

	/**
	 * 为活动追加GB奖品
	 * 
	 * @author wangwenlong
	 * @param passport
	 * @param password
	 * @param activeid
	 * @param gbvalue
	 * @param memo
	 * @return int
	 * @throws QbGetDataException
	 * @throws DocumentException
	 */
	@Override
	public int appendGb(String passport, String password, int activeid,
			int gbvalue, String memo) throws QbGetDataException,
			DocumentException {
		String resultXML = null;
		Document doc1 = null;
		Element flagEle = null;
		String url ="";
		try {
			Face173AccessLog accessLog = getAccessLog();
			accessLog.setCallService(this.getClass().getName());
	
			String message = passport + "#" + password + "#" + activeid + "#"+ gbvalue;
			/**
			 * 将信息进行3des加密
			 */
			String message1=null;
			message1 = DESCoder.desEncrypt(message);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("message", message1);
			url = FaceStringUtil.createURLString(shopURL + addActGold,map,"GBK");
			accessLog.setCallServiceParam(url);
			resultXML = FaceHttpUtil.doRequest(url, null, null,FaceContants.UTF8_ENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultXML);
			doc1 = DocumentHelper.parseText(resultXML);
			Element root1 = doc1.getRootElement();
			flagEle = root1.element("flag");
			return Integer.parseInt(flagEle.getData().toString());
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GB);
			outService.setObject("passport:" + passport);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultXML);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("appendGb throw QbGetDataException" + e.getMessage(),e);
			throw new QbGetDataException("appendGb throw Exception"+ e.getMessage(),e);
		}
	}

	/**
	 * 为用户增加GB
	 * 
	 * @author wangwenlong
	 * @param passport
	 * @param activeid
	 * @param gbvalue
	 * @param memo
	 * @return boolean
	 * @throws QbGetDataException
	 */
	@Override
	public boolean plusGb(String passport, int activeid, int gbvalue,
			String memo) throws QbGetDataException {
		String resultXML = null;
		Document doc = null;
		Element flagEle = null;
		String url="";
		try {
			Face173AccessLog accessLog = getAccessLog();
			accessLog.setCallService(this.getClass().getName());
	
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("act_id", activeid);
			map.put("get_user", passport);
			map.put("gcount", gbvalue);
			map.put("memo", memo);
			map.put("kind", FaceContants.KIND);
			map.put("chk",	MD5.encode(activeid + passport + gbvalue+ FaceContants.GB_ADD_CHECK));
			url = FaceStringUtil.createURLString(shopURL + userReCharge,map,"GBK");
			accessLog.setCallServiceParam(url);
			resultXML = FaceHttpUtil.doRequest(url, null, null,FaceContants.GBKENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultXML);
			doc = DocumentHelper.parseText(resultXML);
			flagEle = doc.getRootElement().element("flag");
			return "1".equals(flagEle.getData()) ? true : false;
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GB);
			outService.setObject("passport:" + passport);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultXML);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("plusGb throw QbGetDataException" + e.getMessage(),e);
			throw new QbGetDataException("plusGb throw Exception"+ e.getMessage(),e);
		}
	}

	/**
	 * 为用户减GB
	 * 
	 * @author wangwenlong
	 * @param passport
	 * @param gbvalue
	 * @param memo
	 * @param channelId
	 * @return boolean
	 * @throws QbGetDataException
	 */
	@Override
	public MinusGbResult minusGb(String passport, int gbvalue, String memo,
			int channelId) throws QbGetDataException {

		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pay_user", passport);
		map.put("gcount", gbvalue);
		map.put("memo", memo);
		map.put("channel_id", channelId);
		map.put("chk", MD5.encode(passport + gbvalue + FaceContants.GB_SUB_CHECK));
		String url = FaceStringUtil.createURLString(shopURL + userChargeBack,map,"GBK");
		accessLog.setCallServiceParam(url);
		String resultXML = null;
		try {
			resultXML = FaceHttpUtil.doRequest(url, null, null,FaceContants.GBKENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultXML);
			resultXML = resultXML.trim();
			if("1".equals(resultXML)){
				return MinusGbResult.SUCCESS;
			}
			if("4".equals(resultXML)){
				return MinusGbResult.NOTRNOUGH;
			}else{
				return MinusGbResult.FAIL;
			}
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_GB);
			outService.setObject("passport:" + passport);
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultXML);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("minusGb throw QbGetDataException" + e.getMessage(),e);
			throw new QbGetDataException("plusGb throw Exception"+ e.getMessage(),e);
		}
	}

	/**
	 * 获取用户当前GB
	 * 
	 * @author wangwenlong
	 * @param
	 * @return int
	 * 
	 */
	@Override
	public int getUserGb(String userName) {

		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_name", userName);
		// 消费类型
		map.put("kind", AccountKind.CONSUME.getValue());
		String url = FaceStringUtil.createURLString(shopURL + getGold, map,"GBK");
		accessLog.setCallServiceParam(url);
		String result = null;
		try {
			result = FaceHttpUtil.doRequest(url, null, null,FaceContants.GBKENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(result);
			return Integer.parseInt(result.trim());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("minusGb throw QbGetDataException" + e.getMessage(),e);
			throw new QbGetDataException("minusGb throw Exception"+ e.getMessage(),e);
		}
	}

	private String addActivitys(ActivityInfo info) throws QbGetDataException {

		/**
		 * 增加切面日志
		 */
		Face173AccessLog accessLog = getAccessLog();
		accessLog.setCallService(this.getClass().getName());
		/**
		 * 装填接口参数
		 */
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("qb_id", info.getQbId()); // 本地活动ID
		map.put("act_class", info.getActClass()); // 频道ID
		map.put("act_name", info.getActName()); // 活动名称
		map.put("game_code", info.getGamecode()); // 游戏ID
		map.put("dept", info.getDept()); // 所属部门
		map.put("act_s_time", info.getActStartTime()); // 活动开始时间
		map.put("act_e_time", info.getActEndTime()); // 活动结束时间
		map.put("act_memo", info.getActMemo()); // 活动描述
		map.put("chk", GBKMD5.encode(info.getActName() + FaceContants.ADD_ACT_CHK));
		/**
		 * 生成URL
		 */
		String url = FaceStringUtil.createURLString(shopURL + addAct,map,"GBK");
		accessLog.setCallServiceParam(url);
		String resultXML = null;
		/**
		 * 请求173接口获取返回数据
		 */
		try {
			resultXML = FaceHttpUtil.doRequest(url, null, null,FaceContants.GBKENCODE);
			/**
			 * 将返回结果打印日志
			 */
			outServiceLog.getReturnLog(resultXML);
			return resultXML;
		} catch (Exception e) {
			e.printStackTrace();
			OutService outService = new OutService();
			outService.setService(url);
			outService.setType(FaceContants.FAIL_ACTIVITY);
			outService.setObject("gamecode" + info.getGamecode());
			outService.setMethod(this.getClass().getName());
			outService.setMemo(resultXML);
			outServiceLog.saveOutServiceFail(outService);
			logger.error("addActivitys throw QbGetDataException"+ e.getMessage(),e);
			throw new QbGetDataException("addActivitys throw Exception"+ e.getMessage(),e);
		}
		
	}
}
